import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Text,
  ListView,
  Image
} from 'react-native';


export default class lvtest extends Component {
  static navigationOptions = {
    title: '数据列表',
  };
  constructor(props){
    super(props);

    this.state = {
      data: null,
    };
  };

  render() {
    if(!this.state.data){
      return(
          <Text>loading...</Text>
      );
    } else {
      return (
        <ListView
          dataSource={this.state.data}
          renderRow={(rowData) => this.renderRow(rowData)}>
        </ListView>
      );
    }
  }

//fetch是一个RN中组件的生命周期回调函数，会在组件渲染后回调
  componentDidMount(){
  
    fetch('http://www.imooc.com/api/teacher?type=4&num=30',
      {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        }
  
    })
    .then((response) => response.json())
    .then((jsonData) => {
      this.setState({
        data: new ListView.DataSource({rowHasChanged: (r1,r2) => r1!==r2 }).cloneWithRows(jsonData.data),
      });
    })
    .catch((error) => {
      alert(error);
    });
  }


  // 返回listview的一行
  renderRow(rowData){
    return(
      <View 
        style = {styles.lvRow}>
          <Image 
            style = { styles.img }
            source = { { uri: rowData.picSmall } }/>
        <View 
          style = { styles.textView }>
          <Text
            style = { styles.textTitle }
            numberOfLines = { 1 }>
            { rowData.name }
          </Text>
          <Text
            style = { styles.textContent }>
            { rowData.description }
          </Text>
        </View>
      </View>
    )
  }
}



const styles = StyleSheet.create({
  lvRow: {
    flex: 1,
    flexDirection: 'row',
    padding: 10,
  },
  textView: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 5,
  },

  textTitle: {
    flex: 1,
    textAlign: 'center',
    color: '#f00',
  },

  textContent: {
    flex: 1,
    fontSize: 11,
    color: '#000',
    textAlign: 'center',
  },

  img: {
    height: 55,
    width: 100,
  }
});
